package com.boarsoft.boar.soagov.alertmanager;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boarsoft.boar.soagov.monitor.MonitorService;
import com.boarsoft.common.util.RandomUtil;
import com.boarsoft.soagov.bean.AlertMonitorData;

@RestController
@RequestMapping("/alertmanager")
public class WebhookAction {
	private static final Logger log = LoggerFactory.getLogger(WebhookAction.class);

	@Autowired
	protected MonitorService monitorSvc;

	/**
	 * 
	 * @param body
	 * @return
	 */
	@RequestMapping("/webhook.do")
	public String webhook(@RequestBody String body) {
		log.info("Webhook received: {}", body);

		JSONObject jo = JSON.parseObject(body);
		List<JSONObject> alerts = jo.getJSONArray("alerts")//
				.toJavaList(JSONObject.class);
		for (JSONObject a: alerts) {
			JSONObject lb = a.getJSONObject("labels");
			String an = a.getString("alertname");
			if ("InstanceDown".equals(an)) {
				String addr = lb.getString("instance");
				AlertMonitorData d = new AlertMonitorData();
				d.setId(RandomUtil.randomUUID());
				d.setKey("prometheus.down");
				String[] aa = addr.split(":");
				d.setIp(aa[0]);
				d.setPort(Integer.parseInt(aa[1]));
				monitorSvc.put(d);
			}
		}
		return "success";
	}

}